const router = require("express").Router();
const { Admin } = require("../models");
const assert = require("http-assert");
const { jwt_secret } = require("../config/index");
const { compareSync } = require("bcrypt");

router.post("/", async (req, res) => {
  // 1. 根据用户名找用户
  const { username, password } = req.body;
  assert(username, 412, "请填写用户名");
  assert(password, 412, "请填写密码");

  const user = await Admin.findOne({
    where: { username },
  });
  assert(user, 412, "用户名或密码错误");

  // 2. 校验密码, 对比hash(123456) $2b$10$zvz96nKnpz6QrGrNFOZ0lOhrN52C9Itp5pJ7eow7PcOjgfjEC9Toy
  const isValid = compareSync(password, user.password);
  assert(isValid, 412, "用户名或密码错误");

  // 3. 返回token
  const { id } = user;
  const jwt = require("jsonwebtoken");
  const token = jwt.sign({ id }, jwt_secret);
  res.json({ token, id, username });
});

module.exports = router;
